package com.example.springbootrabbitmq.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootrabbitmq.constant.Constant;
import com.example.springbootrabbitmq.entity.MessageLog;
import com.example.springbootrabbitmq.entity.TOrder;
import com.example.springbootrabbitmq.mapper.MessageLogMapper;
import com.example.springbootrabbitmq.producer.OrderSender;
import com.example.springbootrabbitmq.utils.FastJsonConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author HL
 */
@Component
public class ReTryMessageTask {

    @Autowired
    private OrderSender orderSender;

    @Autowired
    private MessageLogMapper messageLogMapper;

    @Scheduled(initialDelay = 3000, fixedDelay = 10000)
    public void reSend() {
        System.out.println("-------------定时任务开始--------------");
        QueryWrapper<MessageLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0");
        queryWrapper.le("next_try", LocalDateTime.now());
        List<MessageLog> list = messageLogMapper.selectList(queryWrapper);
        list.forEach(messageLog -> {
            if (messageLog.getTryCount() >= 3) {
                /**
                 * 尝试3次重发，设为发送失败
                 */
                messageLog.setStatus(Constant.ORDER_FAIL);
                messageLog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                messageLogMapper.updateById(messageLog);
            } else {
                messageLog.setTryCount(messageLog.getTryCount()+1);
                messageLog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                messageLogMapper.updateById(messageLog);
                TOrder TOrder = FastJsonConverUtil.jsonToObj(messageLog.getMessage());
                /**
                 * 消息重发
                 */
                try {
                    orderSender.sendOrder(TOrder);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}
